// 用户相关接口
package api

import (
	. "gin-admin-api/core"
	"gin-admin-api/model"
	"gin-admin-api/result"
	util "gin-admin-api/utils"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"strconv"
	"time"
)

// CreateSysAdmin 新增用户
// @Summary 新增用户
// @Tags 用户相关接口
// @Produce json
// @Description 新增用户
// @Param data body model.AddSysAdminDto true "data"
// @Success 200 {object} result.Result
// @Router /api/sysAdmin/add [post]
func CreateSysAdmin(c *gin.Context) {
	var dto model.AddSysAdminDto
	_ = c.BindJSON(&dto)
	err := validator.New().Struct(dto)
	if err != nil {
		result.Failed(c, int(result.ApiCode.MissParameter), result.ApiCode.GetMessage(result.ApiCode.MissParameter))
		return
	}
	// 判断用户名是否已存在
	if GetSysAdminByUserName(dto.Username).ID > 0 {
		result.Failed(c, int(result.ApiCode.UsernameAlreadyExists), result.ApiCode.GetMessage(result.ApiCode.UsernameAlreadyExists))
		return
	}
	//新增用户
	Db.Create(&model.SysAdmin{
		Username: dto.Username,
		Nickname: dto.Nickname,
		Password: util.EncryptionMd5(dto.Password),
		Phone:    dto.Phone,
		Email:    dto.Email,
		Sex:      dto.Sex,
		Note:     dto.Note,
		Status:   dto.Status,
		CreateTime: util.HTime{
			Time: time.Now(),
		},
	})
	//新增用户角色表信息
	sysAdminExists := GetSysAdminByUserName(dto.Username)
	Db.Create(&model.SysAdminRole{
		AdminId: sysAdminExists.ID,
		RoleId:  dto.RoleId,
	})
	result.Success(c, gin.H{})
}

// GetSysAdminByName 根据用户名查询用户
func GetSysAdminByUserName(username string) (sysAdmin model.SysAdmin) {
	Db.Where("username = ?", username).First(&sysAdmin)
	return sysAdmin
}

// GetSysAdminInfo 根据id查询用户信息
// @Summary  根据id查询用户信息
// @Tags 用户相关接口
// @Produce json
// @Description 根据id查询用户信息
// @Param id query int false "用户id"
// @Success 200 {object} result.Result{data=model.AddSysAdminInfoDto}
// @Router /api/sysAdmin/info [get]
func GetSysAdminInfo(c *gin.Context) {
	Id, _ := strconv.Atoi(c.Query("id"))
	var sysAdmin model.AddSysAdminInfoDto
	Db.Table("sys_admin").
		Select("sys_admin.*,sys_admin_role.role_id").
		Joins("left join sys_admin_role on sys_admin.id = sys_admin_role.admin_id").
		Joins("left join sys_role on sys_admin_role.role_id = sys_role.id").
		First(&sysAdmin, Id)
	result.Success(c, sysAdmin)
}
